/*
 * @Date: 2024-01-04 10:21:36
 * @LastEditors: lyx
 * @LastEditTime: 2024-01-30 16:05:43
 * @FilePath: \mt-middleware-server\src\filters\feishu-exception\feishu-exception.filter.ts
 * @Description:
 */
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpStatus,
  Inject,
} from '@nestjs/common';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { getReqMainInfo } from 'utils/common/getReqMainInfo';
import { Logger } from 'winston';

@Catch()
export class FeishuExceptionsFilter implements ExceptionFilter {
  constructor(
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  ) {}

  catch(exception: Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const res = (exception as any)?.response?.data ?? {};
    console.error('typeof exception==>', typeof exception);
    console.error('exception==>', exception);
    this.logger.error('FeishuExceptionsFilter', {
      status: HttpStatus.SERVICE_UNAVAILABLE,
      req: getReqMainInfo(request),
      res: res,
    });
    response.status(HttpStatus.SERVICE_UNAVAILABLE).send({
      isSuccess: false,
      status: false,
      code: res?.code,
      timestamp: new Date().toISOString(),
      path: request.url,
      msg: res?.msg ?? '',
      content: res?.error ?? '',
    });
  }
}
